package com.xunshangwang.pinhaohuo.ui.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.RequestParams;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.decorations.OffsetItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Address;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.ui.activities.address.AddAddressActivity;
import com.xunshangwang.pinhaohuo.ui.activities.address.EditAddressActivity;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Queue;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;
import tool.library.adapter.BaseRecyclerAdapter;

/**
 * Created by xzp on 16/1/28.
 */
public class MyAddressActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener,
        SwipeRefreshLayout.OnRefreshListener,View.OnClickListener{
    private RecyclerView mRecycler;
    private LoadLayout mLoad;
    private RefreshLayout mRefresh;
    private Button mAddAddressBtn;
    private AddressAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_address);
        mRecycler= (RecyclerView) this.findViewById(R.id.my_address_list);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.addItemDecoration(new OffsetItemDecoration(this, R.dimen.address_list_offset));
        mAdapter=new AddressAdapter(this);
        mAdapter.setOnItemClickListener(this);
        mRecycler.setAdapter(mAdapter);
        mLoad= (LoadLayout) this.findViewById(R.id.load_layout);
        mRefresh= (RefreshLayout) this.findViewById(R.id.refresh_layout);
        mRefresh.setOnRefreshListener(this);
        mAddAddressBtn= (Button) this.findViewById(R.id.add_address_btn);
        mAddAddressBtn.setOnClickListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        },150);
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        if(mRefresh.isRefreshing() || TextUtils.equals("DEFAULT",mAdapter.getList().get(position).getStatus()))
            return;
        requestSetDefaultAddress(position);
    }
    private void requestSetDefaultAddress(final int position){
        JSONObject jsonObject=new JSONObject();
        try {
           // jsonObject.put("address_id", mAdapter.getList().get(position).getAddress_id());
            jsonObject.put("status","DEFAULT");
        } catch (JSONException e) {
            return;
        }
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=addresses");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&address_id="+mAdapter.getList().get(position).getAddress_id());
        HttpTool.putJson(this, builder.toString(), jsonObject, new JsonHttpHandler<Void>() {
            @Override
            public Void parseData(JSONObject object) throws Throwable {
                return null;
            }

            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Void response) {
                for (int i = 0; i < mAdapter.getList().size(); i++) {
                    if (TextUtils.equals("DEFAULT", mAdapter.getList().get(i).getStatus())) {
                        mAdapter.getList().get(i).setStatus("COMMON");
                        mAdapter.notifyItemChanged(i);
                        break;
                    }
                }
                mAdapter.getList().get(position).setStatus("DEFAULT");
                mAdapter.notifyItemChanged(position);
            }
        });
    }
    @Override
    public void onRefresh() {
        requestAddressList();
    }
    private void requestAddressList(){
        HttpTool.get(this, "?g=Api&m=Weuser&a=addresses&token=" + getMainApplication().getToken(), new JsonHttpHandler<List<Address>>() {
            @Override
            public List<Address> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("address_list"), Address.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Address> response) {
                mAdapter.setList(response);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add_address_btn:
                startActivityForResult(new Intent(this, AddAddressActivity.class),0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK)
            return;
        switch (requestCode){
            case 0:
            case 1:
                if(!mRefresh.isRefreshing()){
                    mRefresh.setRefreshing(true);
                    onRefresh();
                }
                break;
        }
    }
    private void requestDelete(final int position){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=address");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&address_id="+mAdapter.getList().get(position).getAddress_id());
        HttpTool.delete(this, builder.toString(), new JsonHttpHandler<Void>() {
            @Override
            public Void parseData(JSONObject object) throws Throwable {
                return null;
            }

            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Void response) {
                ToastTool.showToast("删除成功");
                mAdapter.getList().remove(position);
                mAdapter.notifyItemRemoved(position);
            }
        });
    }
    private class AddressAdapter extends BaseRecyclerAdapter<Address>{
        public AddressAdapter(Context context) {
            super(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view=getLayoutInflater().inflate(R.layout.my_address_item,parent,false);
            return new AddressHolder(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            AddressHolder addressHolder= (AddressHolder) holder;
            Address address=getList().get(position);
            addressHolder.receiveNameText.setText(address.getReceive_name());
            addressHolder.addressNameText.setText(address.getFull_address());
            addressHolder.defaultAddressBox.setChecked(TextUtils.equals(address.getStatus(),"DEFAULT"));
            if(address.getMobile()!=null){
                StringBuilder builder=new StringBuilder();
                builder.append(address.getMobile().substring(0,3));
                builder.append("****");
                builder.append(address.getMobile().substring(address.getMobile().length()-4));
                addressHolder.phoneText.setText(builder.toString());
            }
        }
        private  class AddressHolder extends ClickableViewHolder{
            TextView receiveNameText,phoneText,addressNameText;
            CheckBox defaultAddressBox;
            //TextView editAddressBtn,delAddressBtn;
            public AddressHolder(View itemView) {
                super(itemView);
                receiveNameText= (TextView) itemView.findViewById(R.id.receive_name_text);
                phoneText= (TextView) itemView.findViewById(R.id.mobile_phone_text);
                addressNameText= (TextView) itemView.findViewById(R.id.address_name_text);
                defaultAddressBox= (CheckBox) itemView.findViewById(R.id.default_address_check_box);
                itemView.findViewById(R.id.edit_address_btn).setOnClickListener(this);
                itemView.findViewById(R.id.delete_address_btn).setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                final int position=getAdapterPosition();
                if(position==RecyclerView.NO_POSITION)
                    return;
                switch (v.getId()){
                    case R.id.edit_address_btn:
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("address", getList().get(position));
                        Intent intent=new Intent(MyAddressActivity.this, EditAddressActivity.class);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 1);
                        break;
                    case R.id.delete_address_btn:
                        if(!mRefresh.isRefreshing()){
                            AlertDialog.Builder builder=new AlertDialog.Builder(MyAddressActivity.this);
                            builder.setMessage("你确定删除这条地址吗");
                            builder.setNegativeButton("取消", null);
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requestDelete(position);
                                }
                            });
                            builder.show();
                        }
                        break;
                    default:
                        super.onClick(v);
                        break;
                }

            }
        }
    }
}
